<template>
	<div :style="{
		display: 'flex',
		flexDirection: direction,
		height: '100%',
		...style,
	}" ref="containerRef">
		<slot />
	</div>
</template>
<script lang="ts" setup>
import {
	PropType,
	provide,
	ref,
	CSSProperties,
	onMounted,
	onUnmounted,
} from "vue";
import { IResizerProps } from "./types";

const props = defineProps({
	direction: {
		type: String as PropType<"column" | "row">,
		default: "column",
	},
	sizes: Array as PropType<number[]>,
	style: Object as PropType<CSSProperties>,
	gap: {
		type: Number,
		default: 10,
	},
	showHandler: {
		type: Boolean,
		default: true,
	},
	handlerColor: {
		type: String,
		default: "#2e63ff",
	},
	handlerSize: {
		type: Number,
		default: 3,
	},
	storageKey: String,
});
const reactiveSize = ref<number[]>(props.sizes);
const containerRef = ref<HTMLElement>();
function cacheSize() {
	localStorage.setItem(
		props.storageKey,
		JSON.stringify(reactiveSize.value)
	);
}
onMounted(() => {
	if (props.storageKey && localStorage.getItem(props.storageKey)) {
		try {
			reactiveSize.value = JSON.parse(
				localStorage.getItem(props.storageKey)
			);
		} catch { }
	}
	if (props.storageKey) {
		window.onbeforeunload = () => {
			cacheSize();
		}
	}
});
onUnmounted(() => {
	if (props.storageKey) {
		cacheSize();
	}
})
provide<IResizerProps>("vue_resizer", {
	direction: props.direction as unknown as IResizerProps["direction"],
	sizes: reactiveSize,
	containerRef,
	gap: props.gap,
	showHandler: props.showHandler,
	handlerColor: props.handlerColor,
	handlerSize: props.handlerSize,
});
</script>
